<script setup lang="ts">
import {
  useDateFormat,
  useFetch,
  useStorage,
  useTimeoutPoll
} from '@vueuse/core'
import { ref, type Ref } from 'vue'
import type { EventList } from '@/types'

import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
import { mapIdName } from '@/api/constants'
dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

const textarea = ref(mapIdName.map((item) => item.id).join('\n') || '')
let requestArr: {
  execute: (throwOnFailed?: boolean | undefined) => Promise<any>
  data: Ref<EventList>
}[] = []
let responseArr = useStorage('resList', ref<EventList[]>([]))
let index: number
let active: Ref<boolean>

// 只显示几天之内没有提交的同学
const timeOutDay = 3

const initArrays = () => {
  const token = '4e239998f5f0c44e30fac293adf8689d'
  responseArr.value = []
  requestArr = []
  const arr = textarea.value.split('\n').filter((i) => i)
  arr.forEach((user) => {
    const { execute, data } = useFetch<EventList>(
      `/api/${user}?limit=5&access_token=${token}`,
      {
        immediate: false
      }
    ).json()
    requestArr.push({
      execute,
      data
    })
  })
}
const nextRes = async () => {
  if (!requestArr) return
  if (!responseArr.value) responseArr.value = []

  const { execute, data } = requestArr[index]
  await execute()
  responseArr.value.push(data.value)

  index++

  if (index === requestArr.length) {
    console.log('到底了')
    active.value = false
  }
}

const start = () => {
  console.log(12)

  initArrays()

  index = 0
  const { isActive } = useTimeoutPoll(nextRes, 1000)
  active = isActive
  active.value = true
}

const convertId2Name = (id: string) => {
  return mapIdName.find((item) => item.id === id)?.name || '未知'
}

const formatDate = (row: {}, col: {}, val: string) => {
  return useDateFormat(val, 'MMMD日 HH:mm', { locales: 'zh-Hans-CN' }).value
}
</script>

<template>
  <!-- 数据显示部分 -->
  <div v-for="(eventList, index) in responseArr" :key="index">
    <el-collapse
      accordion
      v-if="
        eventList &&
        dayjs(eventList[0]?.created_at).diff(Date.now(), 'day') < -timeOutDay
      "
    >
      <el-collapse-item>
        <template #title>
          <h4>{{ convertId2Name(eventList[0]?.actor.login) }}</h4>
          <el-divider direction="vertical" />
          <span>{{ eventList[0]?.actor.login }}</span>
          <el-divider direction="vertical" />
          <div
            :class="{
              warning:
                dayjs(eventList[0]?.created_at).diff(Date.now(), 'day') < -timeOutDay
            }"
          >
            最后一次推送: {{ dayjs(eventList[0]?.created_at).fromNow() }}
          </div>
        </template>

        <el-table :data="eventList" stripe border style="width: 100%">
          <el-table-column
            prop="created_at"
            label="时间"
            width="180"
            :formatter="formatDate"
          />
          <el-table-column prop="repo.human_name" label="仓库" width="180" />
          <el-table-column label="提交记录">
            <template v-slot="{ row }">
              <ul v-if="row.payload">
                <li v-for="commit in row.payload.commits" :key="commit.sha">
                  {{ commit.message }}
                </li>
              </ul>
              <div v-else>记录已经丢失</div>
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>
    </el-collapse>
  </div>
  <!-- 交互输入部分 -->
  <el-input
    v-model="textarea"
    :rows="5"
    type="textarea"
    placeholder="Please input"
  />
  <el-button @click="start">开始</el-button>
</template>

<style lang="scss" scoped>
.warning {
  color: #f88;
}
</style>
